
using System;
using System.Collections;
using System.Collections.Generic;

public class CoroutineCenter 
{
	List<Coroutine> mCoroutineList;
	List<Coroutine> mCoroutineToBeAdded;
	List<int> mEnumToBeDeleted;

	public CoroutineCenter() 
	{
		mCoroutineList = new List<Coroutine>();
		mCoroutineToBeAdded = new List<Coroutine>();
		mEnumToBeDeleted = new List<int>();
	}

	~CoroutineCenter() 
	{
	}

	public void Update(float deltaTime)
	{
		deltaTime*=1000;

		UpdateEnumToBeAdded();
		
		IEnumerator it;
		for (int i = 0; i < mCoroutineList.Count; i++)
		{
			mCoroutineList[i].Time -= deltaTime;
			if (mCoroutineList[i].Time > 0)
				continue;

			it = mCoroutineList[i].Iter;
			if (it.MoveNext())
				mCoroutineList[i].Time = float.Parse(it.Current.ToString());
			else
				mEnumToBeDeleted.Add(i);
		}

		UpdateEnumToBeDeleted();
	}

	void UpdateEnumToBeAdded()
	{
		mCoroutineList.AddRange(mCoroutineToBeAdded);
		mCoroutineToBeAdded.Clear();
	}

	void UpdateEnumToBeDeleted()
	{
		for (int i = mEnumToBeDeleted.Count-1; i >=0 ; i--)
			mCoroutineList.RemoveAt(mEnumToBeDeleted[i]);

		mEnumToBeDeleted.Clear();
	}
	
	public IEnumerator StartCoroutine(IEnumerator it)
	{
		return StartCoroutine(it, 0);
	}

	public IEnumerator StartCoroutine(IEnumerator it, float millisecond)
	{
		DebugUtil.Assert(mCoroutineToBeAdded!=null);

		mCoroutineToBeAdded.Add(new Coroutine(it, millisecond));
		return it;
	}
	
	public void StopCoroutine(IEnumerator it)
	{
		for (int i = 0; i < mCoroutineList.Count; i++)
		{
			if (mCoroutineList[i].Iter == it)
			{
				mCoroutineList.RemoveAt(i);
				return ;
			}
		}
	}

	public void StopAllCoroutine()
	{
		DebugUtil.Assert(mCoroutineList != null);
		mCoroutineList.Clear();
		mEnumToBeDeleted.Clear();
	}
}
